import React, { useState, useEffect } from 'react';
import { Card, Spin, Select, DatePicker, Space } from 'antd';
import ReactECharts from 'echarts-for-react';

const { Option } = Select;
const { RangePicker } = DatePicker;

const StockChart = ({ symbol }) => {
  const [chartData, setChartData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [chartType, setChartType] = useState('candlestick');
  const [timeRange, setTimeRange] = useState('1Y');

  useEffect(() => {
    const fetchChartData = async () => {
      try {
        setLoading(true);
        const response = await fetch(`/api/stock/${symbol}/chart`);
        const data = await response.json();
        setChartData(data);
      } catch (error) {
        console.error('获取图表数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (symbol) {
      fetchChartData();
    }
  }, [symbol]);

  const getCandlestickOption = () => {
    if (!chartData || !chartData.price_data) return {};

    const dates = chartData.price_data.map(item => item.date);
    const candlestickData = chartData.price_data.map(item => [
      item.open,
      item.close,
      item.low,
      item.high
    ]);

    // 创建日期到MA值的映射
    const ma20Map = {};
    const ma50Map = {};
    if (chartData.ma_data) {
      chartData.ma_data.forEach(item => {
        ma20Map[item.date] = item.ma20;
        ma50Map[item.date] = item.ma50;
      });
    }

    // 确保MA数据与价格数据的日期对应
    const ma20Data = dates.map(date => ma20Map[date] || null);
    const ma50Data = dates.map(date => ma50Map[date] || null);

    return {
      title: {
        text: `${symbol} 价格走势图`,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function (params) {
          const dataIndex = params[0].dataIndex;
          const candlestickData = chartData.price_data[dataIndex];
          if (!candlestickData) return '';

          const ma20Value = ma20Data[dataIndex];
          const ma50Value = ma50Data[dataIndex];

          let tooltip = `日期: ${candlestickData.date}<br/>
                        开盘: $${candlestickData.open}<br/>
                        收盘: $${candlestickData.close}<br/>
                        最高: $${candlestickData.high}<br/>
                        最低: $${candlestickData.low}<br/>
                        成交量: ${candlestickData.volume.toLocaleString()}`;

          if (ma20Value !== null) {
            tooltip += `<br/>MA20: $${ma20Value.toFixed(2)}`;
          }
          if (ma50Value !== null) {
            tooltip += `<br/>MA50: $${ma50Value.toFixed(2)}`;
          }

          return tooltip;
        }
      },
      legend: {
        data: ['股价', 'MA20', 'MA50'],
        top: 30
      },
      grid: [
        {
          left: '10%',
          right: '8%',
          height: '60%'
        },
        {
          left: '10%',
          right: '8%',
          top: '75%',
          height: '15%'
        }
      ],
      xAxis: [
        {
          type: 'category',
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax'
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false }
        }
      ],
      yAxis: [
        {
          scale: true,
          splitArea: {
            show: true
          }
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1],
          start: 70,
          end: 100
        },
        {
          show: true,
          xAxisIndex: [0, 1],
          type: 'slider',
          top: '88%',
          start: 70,
          end: 100
        }
      ],
      series: [
        {
          name: '股价',
          type: 'candlestick',
          data: candlestickData,
          itemStyle: {
            color: '#52c41a',
            color0: '#f5222d',
            borderColor: '#52c41a',
            borderColor0: '#f5222d'
          }
        },
        {
          name: 'MA20',
          type: 'line',
          data: ma20Data,
          smooth: true,
          connectNulls: false,
          lineStyle: {
            opacity: 0.8,
            color: '#faad14',
            width: 2
          },
          itemStyle: {
            color: '#faad14'
          }
        },
        {
          name: 'MA50',
          type: 'line',
          data: ma50Data,
          smooth: true,
          connectNulls: false,
          lineStyle: {
            opacity: 0.8,
            color: '#1890ff',
            width: 2
          },
          itemStyle: {
            color: '#1890ff'
          }
        },
        {
          name: '成交量',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: chartData.price_data.map(item => item.volume),
          itemStyle: {
            color: function(params) {
              const dataIndex = params.dataIndex;
              const candlestickData = chartData.price_data[dataIndex];
              return candlestickData.close >= candlestickData.open ? '#52c41a' : '#f5222d';
            }
          }
        }
      ]
    };
  };

  const getLineOption = () => {
    if (!chartData || !chartData.price_data) return {};

    const dates = chartData.price_data.map(item => item.date);
    const closePrices = chartData.price_data.map(item => item.close);

    return {
      title: {
        text: `${symbol} 收盘价走势`,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: dates
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: closePrices,
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3
        }
      }]
    };
  };

  if (loading) {
    return (
      <Card>
        <div className="loading-container">
          <Spin size="large" />
          <p>加载图表数据中...</p>
        </div>
      </Card>
    );
  }

  if (!chartData) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          无法获取图表数据
        </div>
      </Card>
    );
  }

  const currentOption = chartType === 'candlestick' ? getCandlestickOption() : getLineOption();

  return (
    <div>
      <Card
        title="价格走势图表"
        extra={
          <Space>
            <Select
              value={chartType}
              onChange={setChartType}
              style={{ width: 120 }}
            >
              <Option value="candlestick">K线图</Option>
              <Option value="line">折线图</Option>
            </Select>
          </Space>
        }
      >
        <div className="chart-container">
          <ReactECharts
            option={currentOption}
            style={{ height: '600px' }}
            opts={{ renderer: 'canvas' }}
          />
        </div>
      </Card>

      <Card title="图表说明" style={{ marginTop: '20px' }} size="small">
        <p>• <strong>K线图:</strong> 显示开盘价、收盘价、最高价、最低价和成交量</p>
        <p>• <strong>MA20:</strong> 20日移动平均线，反映短期趋势（黄色）</p>
        <p>• <strong>MA50:</strong> 50日移动平均线，反映中期趋势（蓝色）</p>
        <p>• <strong>成交量:</strong> 每日交易量，绿色表示上涨，红色表示下跌</p>
        <p style={{color: '#666', fontSize: '12px'}}>
          <em>注：MA 数据仅在计算周期足够时显示（MA20需要前20个交易日数据，MA50需要前50个交易日数据）</em>
        </p>
      </Card>
    </div>
  );
};

export default StockChart;
